/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

function Validation() {
    this.lists = new List();
    this.tables = new Hashtable();
    this.tables.put("text", 1);
    this.tables.put("string", 2);
    this.tables.put("email", 3);
    this.tables.put("datetime", 4);
    this.tables.put("time", 5);
    this.tables.put("int", 6);
    this.tables.put("float", 6);
    
}
Validation.prototype.addField = function(cond) {
    this.lists.add(cond);
}
Validation.prototype.execute = function() {
    var i = 0;
    var str = new StringBuffer();
    for(i = 0; i < this.lists.size(); i++) {
        var f = this.lists.get(i);
        //alert("f:"+ f);
        str.append(this.validate(f));
    }
    return str.toString();
}
Validation.prototype.checkType = function(type) {
    if( this.tables.get(type) == null ) {
        return -1;
    } else {
        return this.tables.get(type);
    }
    
}
Validation.prototype.validate = function(strCond) {
    var name = "";
    var type = "";
    //alert("str eval:"+ strCond);
    eval(strCond);
    //alert("is type:"+ this.checkType($d(name).type));
    switch( this.checkType(type) ) {
        case 1:
            return this.stringValidate(strCond);
        case 2:
            return this.stringValidate(strCond);
        case 3:
            return this.emailCheck(strCond);
        case 4:
            return this.dateValidate(strCond);
        case 5:
            return this.timeValidate(strCond);
        case 6:
            return this.numberValidate(strCond);
    }
    return "";
}
Validation.prototype.timeValidate = function(strCond) {
    var name = "";
    var label = "";
    var require = true;
    var handle = "";
    var release = "";
    eval(strCond);
    if( require == true ) {
        var str = new StringBuffer();
        if( $d(name).value == "" ) {
            str.append(""+ label + " : Invalid Time.");
        } else {
            str.append(this.TrimAll(this.checkShortTime(name)));
        }
        if( str.toString().length > 0 ) {
            if( handle != "" ) {
                eval(""+handle+"('"+name+"','"+label +" :" +str.toString()+"')");
            }
        } else {
            if( release != "" ) {
                eval(""+release+"('"+name+"')");
            }
        }
    }
}
Validation.prototype.dateValidate = function(strCond) {
    var name = "";
    var label = "";
    var require = true;
    var handle = "";
    var release = "";
    eval(strCond);
    if( require == true ) {
        var str = this.TrimAll(this.checkDate(name));
        if( str.length > 0 ) {
            if( handle != "" ) {
                eval(""+handle+"('"+name+"','"+label +" :" +str.toString()+"')");
            }
        } else {
            if( release != "" ) {
                eval(""+release+"('"+name+"')");
            }
        }
    }
    return str;
}
Validation.prototype.numberValidate = function(strCond) {
    var min = -1;
    var max = -1;
    var name = "";
    var label = "";
    var type = "";
    var value = "";
    var require = true;
    var handle = "";
    var release = "";
    eval(strCond);
    if( value != "") {
        if( type == "int" ) {
            $d(name).value = parseInt(value);
        }
        if( type == "float" ) {
            $d(name).value = parseFloat(value);
        }
    }
    if( require == false ) {
        return "";
    }
    var str = new StringBuffer();
    if( type == "int" ) {
        if( !this.isInteger($d(name).value) ) {
            str.append(""+label +" : "+ $d(name).value +" invalid Integer.\n");
        }
        if( min > parseInt($d(name).value) ) {
            str.append(""+label +" : "+ $d(name).value +" less than "+ min +".\n");
        }
        if( max < parseInt($d(name).value)) {
            str.append(""+label +" : "+ $d(name).value +" more than "+ min +".\n");
        }
    } else {
        if( type == "float" ) {
            //alert('in float');
            if( $d(name).value == "" ) {
                str.append(""+ label +" : "+ $d(name).value +" Invalid Float.\n");
            } else {
                if( !this.isNumeric($d(name).value) ) {
                    str.append(""+ label +" : "+ $d(name).value +" Invalid Float.\n");
                } else {
                    if( min > parseFloat($d(name).value) ) {
                        str.append(""+label +" : "+ $d(name).value +" less than "+ min +".\n");
                    } else {
                        if( max < parseFloat($d(name).value)) {
                            str.append(""+label +" : "+ $d(name).value +" more than "+ min +".\n");
                        }
                    }
                }
            }
        }
    }
    var strM = this.TrimAll(str.toString());
    //alert("str["+strM+"]");
    if( strM.length > 0 ) {
        if( handle != "" ) {
            eval(""+handle+"('"+name+"','"+strM+"')");
        }
    } else {
        if( release != "" ) {
            eval(""+release+"('"+name+"')");
        }
    }
    return strM;
}
Validation.prototype.stringValidate = function(strCond) {
    var min = 0;
    var max = 0;
    var name = "";
    var label = "";
    var type = "";
    var value = "";
    var require = true;
    var handle = "";
    var release = "";
    eval(strCond);
    if( require == false ) {
        return "";
    }
    if( value.length != 0 ) {
        if( $d(name).value == null ) {
            $d(name).value = value;
        }
    }
    var str = new StringBuffer();
    switch( this.checkType(type) ) {
        case 2:
            label = ( label == "" ) ? name : label;
            if( $d(name).value == null ) {  
                str.append(""+ label + " is require.");
                break
            }
            if( $d(name).value.length == 0 ) {  
                str.append(""+ label + " is require.");
                break
            }
            if( $d(name).value.length < min ) {
                str.append(label);
                str.append(" will must less then "+ min);
            }
            if( $d(name).value.length > max ) {
                if( str.length() > 0 ) {
                    str.append(",");
                }
                str.append(label);
                str.append(" will must more then "+ max);
                        
            }
            str.append("\n");
            break;
    }
    var strM = str.toString();
    strM = this.TrimAll(strM);
    if( strM.length > 0 ) {
        if( handle != "" ) {
            eval(""+handle+"('"+name+"','"+str.toString()+"')");
        }
    } else {
        if( release != "" ) {
            eval(""+release+"('"+name+"')");
        }
    }
    return strM;
}
Validation.prototype.checkDate = function(field) { 
    var minYear = 1902;
    var minT = 0;
    var maxT = 59;
    var maxYear = (new Date()).getUTCFullYear();
    var errorMsg = ""; 
    // regular expression to match required date format
    //alert("pass 1");
    if($d(field).value != "") {
        //alert("pass 2");
        var re = /^(\d{4})\-(\d{1,2})\-(\d{1,2}) (\d{1,2})\:(\d{1,2})\:(\d{1,2})$/;
        var txtDate = $d(field).value;
        var regs = txtDate.match(re);
     
        if( regs != null ) 
        {
            //alert("pass 3");
            if(regs[3] < 1 || regs[3] > 31) 
            {
                errorMsg = "Invalid value for day: " + regs[1]; 
            } else if(regs[2] < 1 || regs[2] > 12) {
                errorMsg = "Invalid value for month: " + regs[2];
            } else if(regs[1] < minYear || regs[1] > maxYear) {
                errorMsg = "Invalid value for year: " + regs[1] + " - must be between " + minYear + " and " + maxYear;
            } else if(regs[4] < minT || regs[4] > maxT) {
                errorMsg = "Invalid value for Hour: " + regs[4] + " - must be between " + minT + " and " + maxT;
            } else if(regs[5] < minT || regs[5] > maxT) {
                errorMsg = "Invalid value for Minute: " + regs[5] + " - must be between " + minT + " and " + maxT;
            } else if(regs[6] < minT || regs[6] > maxT) {
                errorMsg = "Invalid value for Second: " + regs[6] + " - must be between " + minT + " and " + maxT;
            }
            
        } else {
            //alert("pass 4");
            errorMsg = "Invalid date format: " + $d(field).value;
        }
    } else {
        //alert("pass 5");
        errorMsg = "Empty date not allowed!";
    }
    if(errorMsg != "") {
        //alert("pass 6");
        //alert(errorMsg);
        //$d(field).focus();
        return errorMsg;
    }
    return "";
}
Validation.prototype.checkShortTime = function(field) { 
    var errorMsg = ""; 
    // regular expression to match required time format 
    re = /^(\d{1,2}):(\d{2})$/;
    if($d(field).value != '') {
        var regs = $d(field).value.match(re)
        //// 24-hour time format 
        if( regs != null ) {
            if(regs[1] < 0 || regs[1] > 23) {
                errorMsg = "Invalid value for hours: " + regs[1];
            }
            else {
                if(!errorMsg && regs[2] > 59) {
                    errorMsg = "Invalid value for minutes: " + regs[2];
                }
            }
        } else {
            errorMsg = "Invalid time format: " + field.value;
        }
    }
    if(errorMsg != "") {
        //alert(errorMsg);
        //field.focus();
        return errorMsg;
    }
    return "";
}
Validation.prototype.checkTime = function(field) { 
    var errorMsg = ""; 
    // regular expression to match required time format 
    re = /^(\d{1,2}):(\d{2})(:00)?([ap]m)$/;
    if( $d(field).value != '') {
        var regs = field.value.match(re);
        if( regs != null ) {
            if(regs[4]) { 
                // 12-hour time format with am/pm 
                if(regs[1] < 1 || regs[1] > 12) {
                    errorMsg = "Invalid value for hours: " + regs[1];
                }
            } else { 
                //// 24-hour time format 
                if(regs[1] > 23) {
                    errorMsg = "Invalid value for hours: " + regs[1];
                }
            }
            if(!errorMsg && regs[2] > 59) {
                errorMsg = "Invalid value for minutes: " + regs[2];
            }
        } else {
            errorMsg = "Invalid time format: " + field.value;
        }
    }
    if(errorMsg != "") {
        //alert(errorMsg);
        //field.focus();
        return errorMsg;
    }
    return "";
}
Validation.prototype.emailCheck = function(strCond) {
    var name = "";
    var label = "";
    var type = "";
    var value = "";
    var require = true;
    var handle = "";
    var release = "";
    var atpos=0;
    var dotpos=0;
    eval(strCond);
    var x = $d(name).value;
    
    if( require == false ) {
        return "";
    }
    
    if( require == true ) {
        var str = new StringBuffer();
        if( x == "" ) {
            str.append(""+ label + " : Invalid Email.");
        } else {
            atpos=x.indexOf("@");
            dotpos=x.lastIndexOf(".");
            if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
            {
                str.append("Invalid e-mail address.");
            }
        }
        if( str.toString().length > 0 ) {
            if( handle != "" ) {
                eval(""+handle+"('"+name+"','"+label +" :" +str.toString()+"')");
            }
        } else {
            if( release != "" ) {
                eval(""+release+"('"+name+"')");
            }
        }
    }

    return str.toString();					
}
Validation.prototype.LTrim = function(str){
    if (str==null){
        return null;
    }
    for(var i=0;str.charAt(i)==" ";i++);
    return str.substring(i,str.length);
}
Validation.prototype.RTrim = function(str){
    if (str==null){
        return null;
    }
    for(var i=str.length-1;str.charAt(i)==" ";i--);
    return str.substring(0,i+1);
}
Validation.prototype.Trim = function(str){
    return this.LTrim(this.RTrim(str));
}
Validation.prototype.LTrimAll = function(str) {
    if (str==null){
        return str;
    }
    for (var i=0; str.charAt(i)==" " || str.charAt(i)=="\n" || str.charAt(i)=="\t"; i++);
    return str.substring(i,str.length);
}
Validation.prototype.RTrimAll = function(str) {
    if (str==null){
        return str;
    }
    for (var i=str.length-1; str.charAt(i)==" " || str.charAt(i)=="\n" || str.charAt(i)=="\t"; i--);
    return str.substring(0,i+1);
}
Validation.prototype.TrimAll = function(str) {
    return this.LTrimAll(this.RTrimAll(str));
}
//-------------------------------------------------------------------
// isNull(value)
//   Returns true if value is null
//-------------------------------------------------------------------
Validation.prototype.isNull= function(val){
    return(val==null);
}

//-------------------------------------------------------------------
// isBlank(value)
//   Returns true if value only contains spaces
//-------------------------------------------------------------------
Validation.prototype.isBlank = function(val){
    if(val==null){
        return true;
    }
    for(var i=0;i<val.length;i++) {
        if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){
            return false;
        }
    }
    return true;
}

//-------------------------------------------------------------------
// isInteger(value)
//   Returns true if value contains all digits
//-------------------------------------------------------------------
Validation.prototype.isInteger = function(val){
    if (this.isBlank(val)){
        return false;
    }
    for(var i=0;i<val.length;i++){
        if(!this.isDigit(val.charAt(i))){
            return false;
        }
    }
    return true;
}

//-------------------------------------------------------------------
// isNumeric(value)
//   Returns true if value contains a positive float value
//-------------------------------------------------------------------
Validation.prototype.isNumeric = function(val){
    return(parseFloat(val,10)==(val*1));
}

//-------------------------------------------------------------------
// isArray(obj)
// Returns true if the object is an array, else false
//-------------------------------------------------------------------
Validation.prototype.isArray = function(obj){
    return(typeof(obj.length)=="undefined")?false:true;
}

//-------------------------------------------------------------------
// isDigit(value)
//   Returns true if value is a 1-character digit
//-------------------------------------------------------------------
Validation.prototype.isDigit = function(num) {
    if (num.length>1){
        return false;
    }
    var string="1234567890";
    if (string.indexOf(num)!=-1){
        return true;
    }
    return false;
}

//-------------------------------------------------------------------
// setNullIfBlank(input_object)
//   Sets a form field to "" if it isBlank()
//-------------------------------------------------------------------
Validation.prototype.setNullIfBlank = function(obj){
    if(this.isBlank(obj.value)){
        obj.value="";
    }
}

//-------------------------------------------------------------------
// setFieldsToUpperCase(input_object)
//   Sets value of form field toUpperCase() for all fields passed
//-------------------------------------------------------------------
Validation.prototype.setFieldsToUpperCase = function(){
    for(var i=0;i<arguments.length;i++) {
        arguments[i].value = arguments[i].value.toUpperCase();
    }
}

//-------------------------------------------------------------------
// disallowBlank(input_object[,message[,true]])
//   Checks a form field for a blank value. Optionally alerts if 
//   blank and focuses
//-------------------------------------------------------------------
Validation.prototype.disallowBlank = function(obj){
    var msg=(arguments.length>1)?arguments[1]:"";
    var dofocus=(arguments.length>2)?arguments[2]:false;
    if (this.isBlank(getInputValue(obj))){
        if(!this.isBlank(msg)){
            alert(msg);
        }
        if(dofocus){
            if (isArray(obj) && (typeof(obj.type)=="undefined")) {
                obj=obj[0];
            }
            if(obj.type=="text"||obj.type=="textarea"||obj.type=="password") {
                obj.select();
            }
            obj.focus();
        }
        return true;
    }
    return false;
}

//-------------------------------------------------------------------
// disallowModify(input_object[,message[,true]])
//   Checks a form field for a value different than defaultValue. 
//   Optionally alerts and focuses
//-------------------------------------------------------------------
Validation.prototype.disallowModify = function(obj){
    var msg=(arguments.length>1)?arguments[1]:"";
    var dofocus=(arguments.length>2)?arguments[2]:false;
    if (this.getInputValue(obj)!=this.getInputDefaultValue(obj)){
        if(!this.isBlank(msg)){
            alert(msg);
        }
        if(dofocus){
            if (isArray(obj) && (typeof(obj.type)=="undefined")) {
                obj=obj[0];
            }
            if(obj.type=="text"||obj.type=="textarea"||obj.type=="password") {
                obj.select();
            }
            obj.focus();
        }
        this.setInputValue(obj,getInputDefaultValue(obj));
        return true;
    }
    return false;
}

//-------------------------------------------------------------------
// commifyArray(array[,delimiter])
//   Take an array of values and turn it into a comma-separated string
//   Pass an optional second argument to specify a delimiter other than
//   comma.
//-------------------------------------------------------------------
Validation.prototype.commifyArray = function(obj,delimiter){
    if (typeof(delimiter)=="undefined" || delimiter==null) {
        delimiter = ",";
    }
    var s="";
    if(obj==null||obj.length<=0){
        return s;
    }
    for(var i=0;i<obj.length;i++){
        s=s+((s=="")?"":delimiter)+obj[i].toString();
    }
    return s;
}

//-------------------------------------------------------------------
// getSingleInputValue(input_object,use_default,delimiter)
//   Utility function used by others
//-------------------------------------------------------------------
Validation.prototype.getSingleInputValue = function(obj,use_default,delimiter) {
    switch(obj.type){
        case 'radio': case 'checkbox':
            return(((use_default)?obj.defaultChecked:obj.checked)?obj.value:null);
        case 'text': case 'hidden': case 'textarea':
            return(use_default)?obj.defaultValue:obj.value;
        case 'password':
            return((use_default)?null:obj.value);
        case 'select-one':
            if (obj.options==null) {
                return null;
            }
            if(use_default){
                var o=obj.options;
                for(var i=0;i<o.length;i++){
                    if(o[i].defaultSelected){
                        return o[i].value;
                    }
                }
                return o[0].value;
            }
            if (obj.selectedIndex<0){
                return null;
            }
            return(obj.options.length>0)?obj.options[obj.selectedIndex].value:null;
        case 'select-multiple':
            if (obj.options==null) {
                return null;
            }
            var values=new Array();
            for(var i=0;i<obj.options.length;i++) {
                if((use_default&&obj.options[i].defaultSelected)||(!use_default&&obj.options[i].selected)) {
                    values[values.length]=obj.options[i].value;
                }
            }
            return (values.length==0)?null:commifyArray(values,delimiter);
    }
    alert("FATAL ERROR: Field type "+obj.type+" is not supported for this function");
    return null;
}

//-------------------------------------------------------------------
// getSingleInputText(input_object,use_default,delimiter)
//   Utility function used by others
//-------------------------------------------------------------------
Validation.prototype.getSingleInputText = function(obj,use_default,delimiter) {
    switch(obj.type){
        case 'radio': case 'checkbox':
            return "";
        case 'text': case 'hidden': case 'textarea':
            return(use_default)?obj.defaultValue:obj.value;
        case 'password':
            return((use_default)?null:obj.value);
        case 'select-one':
            if (obj.options==null) {
                return null;
            }
            if(use_default){
                var o=obj.options;
                for(var i=0;i<o.length;i++){
                    if(o[i].defaultSelected){
                        return o[i].text;
                    }
                }
                return o[0].text;
            }
            if (obj.selectedIndex<0){
                return null;
            }
            return(obj.options.length>0)?obj.options[obj.selectedIndex].text:null;
        case 'select-multiple':
            if (obj.options==null) {
                return null;
            }
            var values=new Array();
            for(var i=0;i<obj.options.length;i++) {
                if((use_default&&obj.options[i].defaultSelected)||(!use_default&&obj.options[i].selected)) {
                    values[values.length]=obj.options[i].text;
                }
            }
            return (values.length==0)?null:commifyArray(values,delimiter);
    }
    alert("FATAL ERROR: Field type "+obj.type+" is not supported for this function");
    return null;
}

//-------------------------------------------------------------------
// setSingleInputValue(input_object,value)
//   Utility function used by others
//-------------------------------------------------------------------
Validation.prototype.setSingleInputValue = function(obj,value) {
    switch(obj.type){
        case 'radio': case 'checkbox':
            if(obj.value==value){
                obj.checked=true;
                return true;
            }else{
                obj.checked=false;
                return false;
            }
        case 'text': case 'hidden': case 'textarea': case 'password':
            obj.value=value;
            return true;
        case 'select-one': case 'select-multiple':
            var o=obj.options;
            for(var i=0;i<o.length;i++){
                if(o[i].value==value){
                    o[i].selected=true;
                }
                else{
                    o[i].selected=false;
                }
            }
            return true;
    }
    alert("FATAL ERROR: Field type "+obj.type+" is not supported for this function");
    return false;
}

//-------------------------------------------------------------------
// getInputValue(input_object[,delimiter])
//   Get the value of any form input field
//   Multiple-select fields are returned as comma-separated values, or
//   delmited by the optional second argument
//   (Doesn't support input types: button,file,reset,submit)
//-------------------------------------------------------------------
Validation.prototype.getInputValue = function(obj,delimiter) {
    var use_default=(arguments.length>2)?arguments[2]:false;
    if (this.isArray(obj) && (typeof(obj.type)=="undefined")) {
        var values=new Array();
        for(var i=0;i<obj.length;i++){
            var v=this.getSingleInputValue(obj[i],use_default,delimiter);
            if(v!=null){
                values[values.length]=v;
            }
        }
        return this.commifyArray(values,delimiter);
    }
    return this.getSingleInputValue(obj,use_default,delimiter);
}

//-------------------------------------------------------------------
// getInputText(input_object[,delimiter])
//   Get the displayed text of any form input field
//   Multiple-select fields are returned as comma-separated values, or
//   delmited by the optional second argument
//   (Doesn't support input types: button,file,reset,submit)
//-------------------------------------------------------------------
Validation.prototype.getInputText = function(obj,delimiter) {
    var use_default=(arguments.length>2)?arguments[2]:false;
    if (this.isArray(obj) && (typeof(obj.type)=="undefined")) {
        var values=new Array();
        for(var i=0;i<obj.length;i++){
            var v=this.getSingleInputText(obj[i],use_default,delimiter);
            if(v!=null){
                values[values.length]=v;
            }
        }
        return this.commifyArray(values,delimiter);
    }
    return this.getSingleInputText(obj,use_default,delimiter);
}

//-------------------------------------------------------------------
// getInputDefaultValue(input_object[,delimiter])
//   Get the default value of any form input field when it was created
//   Multiple-select fields are returned as comma-separated values, or
//   delmited by the optional second argument
//   (Doesn't support input types: button,file,password,reset,submit)
//-------------------------------------------------------------------
Validation.prototype.getInputDefaultValue = function(obj,delimiter){
    return this.getInputValue(obj,delimiter,true);
}

//-------------------------------------------------------------------
// isChanged(input_object)
//   Returns true if input object's value has changed since it was
//   created.
//-------------------------------------------------------------------
Validation.prototype.isChanged = function(obj){
    return(this.getInputValue(obj)!=this.getInputDefaultValue(obj));
}

//-------------------------------------------------------------------
// setInputValue(obj,value)
//   Set the value of any form field. In cases where no matching value
//   is available (select, radio, etc) then no option will be selected
//   (Doesn't support input types: button,file,password,reset,submit)
//-------------------------------------------------------------------
Validation.prototype.setInputValue = function(obj,value) {
    var use_default=(arguments.length>1)?arguments[1]:false;
    if(this.isArray(obj)&&(typeof(obj.type)=="undefined")){
        for(var i=0;i<obj.length;i++){
            this.setSingleInputValue(obj[i],value);
        }
    }
    else{
        this.setSingleInputValue(obj,value);
    }
}
	
//-------------------------------------------------------------------
// isFormModified(form_object,hidden_fields,ignore_fields)
//   Check to see if anything in a form has been changed. By default
//   it will check all visible form elements and ignore all hidden 
//   fields. 
//   You can pass a comma-separated list of field names to check in
//   addition to visible fields (for hiddens, etc).
//   You can also pass a comma-separated list of field names to be
//   ignored in the check.
//-------------------------------------------------------------------
Validation.prototype.isFormModified = function(theform,hidden_fields,ignore_fields){
    if(hidden_fields==null){
        hidden_fields="";
    }
    if(ignore_fields==null){
        ignore_fields="";
    }
    var hiddenFields=new Object();
    var ignoreFields=new Object();
    var i,field;
    var hidden_fields_array=hidden_fields.split(',');
    for (i=0;i<hidden_fields_array.length;i++) {
        hiddenFields[this.Trim(hidden_fields_array[i])]=true;
    }
    var ignore_fields_array=ignore_fields.split(',');
    for (i=0;i<ignore_fields_array.length;i++) {
        ignoreFields[this.Trim(ignore_fields_array[i])]=true;
    }
    for (i=0;i<theform.elements.length;i++) {
        var changed=false;
        var name=theform.elements[i].name;
        if(!this.isBlank(name)){
            var type=theform.elements[i].type;
            if(!ignoreFields[name]){
                if(type=="hidden"&&hiddenFields[name]){
                    changed=this.isChanged(theform[name]);
                }
                else if(type=="hidden"){
                    changed=false;
                }
                else {
                    changed=this.isChanged(theform[name]);
                }
            }
        }
        if(changed){
            return true;
        }
    }
    return false;
}
            